<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

        <QueryFormItem label="操作时间">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="RefreshRight" type="primary" plain round @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
          <el-button icon="Search" type="primary" round @click="handleSearch">{{ $t('form.search') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
<!--        <el-button v-permission="'sys:operation_log:delete'" icon="Delete" plain type="danger" @click="handleBatchDelete">-->
<!--          {{ multipleSelection.length > 0 ? `清理(${multipleSelection.length})` : '清理' }}-->
<!--        </el-button>-->
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #business_type="scope">
              <DictTag v-model="scope.row.business_type" :circle="true" dict-type="sys_operation_type" effect="plain"/>
            </template>

            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="sys_operation_status" effect="plain"/>
            </template>

            <template #time="scope">
              <el-tag v-if="scope.row.time <= 100" effect="plain" style="min-width: 68px" type="success">{{ scope.row.time }}ms</el-tag>
              <el-tag v-else-if="scope.row.time <= 300" effect="plain" style="min-width: 68px" type="primary">{{ scope.row.time }}ms</el-tag>
              <el-tag v-else-if="scope.row.time <= 800" effect="plain" style="min-width: 68px" type="warning">{{ scope.row.time }}ms</el-tag>
              <el-tag v-else effect="plain" style="min-width: 68px" type="danger">{{ scope.row.time }}ms</el-tag>
            </template>

<!--            <template #operations="scope">-->
<!--              <el-button v-permission="'sys:operation_log:list'" link type="info" @click="handleFormOpen(scope.row)">查看</el-button>-->

<!--              <el-popconfirm v-if="hasPermission('sys:operation_log:delete')"-->
<!--                             :key="scope.row.id"-->
<!--                             cancel-button-text="放弃"-->
<!--                             confirm-button-text="确定"-->
<!--                             icon="WarningFilled"-->
<!--                             title="您确定要清理此记录?"-->
<!--                             width="220"-->
<!--                             @confirm="handleDelete([scope.row.id])">-->
<!--                <template #reference>-->
<!--                  <el-button link type="danger">清理</el-button>-->
<!--                </template>-->
<!--              </el-popconfirm>-->
<!--            </template>-->
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <OperationLogInfo ref="formRef"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElLoading, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { sysOperationLogDelete, sysOperationLogList } from '@/api/api-sys.ts';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth, pickerShortcuts } from '@/utils';
import { DictTag } from '@/components/dict-tag';
import OperationLogInfo from './OperationLogInfo.vue';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import {timeStamp} from "@/utils/validate.ts";
import {convertDateRangeToTimestamps} from "@/utils/util.ts";

defineOptions({name: 'sys-operation-log'});

// 查询
const queryFormData = reactive({
  title: undefined,
  username: undefined,
  ip_address: undefined,
  params: undefined,
  business_type: undefined,
  status: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'plat', label: '操作人员', placeholder: '请输入操作人员', clearable: true, inputType: 'number'},
  {type: 'input', prop: 'mode', label: '系统模块', placeholder: '请输入系统模块', clearable: true,},
  // {type: 'input', prop: 'params', label: '参数内容', placeholder: '请输入参数内容', clearable: true,},
  {type: 'input', prop: 'ip_address', label: '主机地址', placeholder: '请输入主机地址', clearable: true,},
  // {type: 'dict-select', prop: 'business_type', label: '操作类型', placeholder: '请选择操作类型', dictType: 'sys_operation_type', clearable: true,},
  // {type: 'dict-select', prop: 'status', label: '操作状态', placeholder: '请选操作状态', dictType: 'sys_operation_status', clearable: true,},
]);

// 列表相关
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const pickerDate = ref([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('sys:operation_log:delete')) count += 2
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  // {type: 'selection', width: 45, hidden: operateWidth.value == 0},
  {prop: 'id', label: '编号', width: 105, align: 'center'},
  {prop: 'mode', label: '系统模块', minWidth: 140, align: 'center'},
  {prop: 'method', label: '操作类型', minWidth: 115, align: 'center'},
  {prop: 'plat', label: '操作人员', minWidth: 160, align: 'center'},
  {prop: 'ip', label: '主机地址', minWidth: 140, align: 'center'},
  // {prop: 'ip_location', label: '操作地点', minWidth: 160, align: 'center'},
  // {prop: 'status', label: '操作状态', minWidth: 115, align: 'center'},
  // {prop: 'time', label: '执行耗时', minWidth: 110, align: 'center'},
  {prop: 'create_time', label: '操作时间', width: 180, align: 'center',render: (scope, val) => <span>{timeStamp(val) || '-'}</span>},
]);

onBeforeMount(() => {
  // if (operateWidth.value > 0) {
  //   columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  // }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    const date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 查询数据
    const {body} = await sysOperationLogList({
      page: pageQuery.pageNum,
      size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      action:'list',
      ...queryFormData,
      start_time:convertDateRangeToTimestamps(date).startTimestamp,
      end_time:convertDateRangeToTimestamps(date).endTimestamp
    });
    // 结果转换
    tableData.value = body.list;
    totalCount.value = body.pages.count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  clearSelection();
  handleResetForm();
};

/** 添加/修改操作 */
const formRef = ref<any>()
const handleFormOpen = (data: any) => {
  formRef.value.open(data)
};

/** 批量删除操作 */
const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    return;
  }

  // 需要清理的编号
  const itemIds = multipleSelection.value.map((item) => {
    return item.id;
  });

  ElMessageBox({
    title: '操作确认',
    message: h('p', null, [
      '您确定要清理选中的 ',
      h('span', {style: 'font-weight: bold'}, itemIds.length + '条'),
      ' 记录吗？',
    ]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    // 调用函数清理清理
    handleDelete(itemIds);
  }).catch(() => {

  });
}

/** 删除操作 */
const handleDelete = (ids: number[]) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在处理中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  sysOperationLogDelete(ids).then(() => {
    // 提示信息
    ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
    // 清理选中信息
    clearSelection(ids);
    // 刷新列表数据
    handleSearch();
  }).finally(() => loading.close())
};
</script>

<style lang="scss" scoped>

</style>
